﻿// -----------------------------------------------------------------------
// <copyright file="Posts.cs" company="Microsoft">
// TODO: Update copyright text.
// </copyright>
// -----------------------------------------------------------------------

using System.Data;
using System.Linq.Expressions;
using System.Web;
using System.Web.UI.WebControls;
using CamlexNET;
using Microsoft.SharePoint;

namespace LifeInSharePoint.Blog.Business.DAL
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using LifeInSharePoint.Common;

    /// <summary>
    /// TODO: Update summary.
    /// </summary>

    public class Post
    {
        public string CType { get; set; }
        public int Id { get; set; }
        public int CommentCount { get; set; }
        public string Title { get; set; }
        public string Excerpt { get; set; }
        public string PostCategory { get; set; }
        public string RollupImage { get; set; }
        public string PostImage { get; set; }
        public DateTime Modified { get; set; }
        public SPUser ModifiedBy { get; set; }
        public string Url { get; set; }
        public string TimeAgo { get; set; }

        public Post()
        {
        }
    }

    public static class Posts
    {
        public static readonly string ListName = "Pages";
        public static readonly string ContentType = "Life In SharePoint Blog Post";
        public static readonly string ServerTemplate = "850";

        public static class Fields
        {
            public static string CType = "ContentType";
            public static string Id = "ID";
            public static string Title = "Title";
            public static string Excerpt = "LISPPostExcerpt";
            public static string PostCategory = "LISPPostCategory";
            public static string RollupImage = "PublishingRollupImage";
            public static string PostImage = "LISPPostImage";
            public static string Modified = "Modified";
            public static string ModifiedBy = "Editor";
            public static string Url = "FileRef";
        }

        public static class ViewFields
        {
            public static string CType = "<FieldRef Name='ContentType' />";
            public static string Id = "<FieldRef Name='ID' />";
            public static string Title = "<FieldRef Name='Title' />";
            public static string Excerpt = "<FieldRef Name='LISPPostExcerpt' />";
            public static string PostCategory = "<FieldRef Name='LISPPostCategory' />";
            public static string RollupImage = "<FieldRef Name='PublishingRollupImage' />";
            public static string PostImage = "<FieldRef Name='LISPPostImage' />";
            public static string Modified = "<FieldRef Name='Modified' />";
            public static string ModifiedBy = "<FieldRef Name='Editor' />";
            public static string Url = "<FieldRef Name='FileRef' />";
        }

        public static List<Post> getPostsListItemCollection()
        {
            DataTable items = getPostsDataTable();

            List<Post> Posts = new List<Post>();

            foreach (DataRow item in items.Rows)
            {
                string content = string.Empty;

                using (SPWeb web = SPContext.Current.Site.OpenWeb(new Guid(item["WebID"].ToString())))
                {
                    //Get the Current SPList insatnce
                    SPList pages = web.Lists[new Guid(item["ListID"].ToString())];
                    //Get the SPListItem for that List by ID
                    SPListItem _workitem = pages.GetItemById(int.Parse(item["ID"].ToString()));

                    //Add to New Post
                    Post _workPost = new Post();

                    //Get Categories and Add to XML
                    SPFieldLookupValueCollection ItemValues = _workitem["LISPPostCategory"] as SPFieldLookupValueCollection;
                    string Categories = "";
                    foreach (SPFieldLookupValue itemValue in ItemValues)
                    {
                        Categories += "<a href='" + HttpContext.Current.Request.Path + "?Category=" + itemValue.LookupValue + "'>" + itemValue.LookupValue + "</a>, ";
                    }
                    _workPost.PostCategory = Categories;
                    _workPost.ModifiedBy = SPUserHelper.GetSPUser(_workitem, "Modified By");
                    _workPost.Title = SPListHelper.GetColumnStringValue(_workitem, "Title");
                    _workPost.Id = _workitem.ID;
                    _workPost.CommentCount = getCommentCount(_workitem.ID);
                    _workPost.Excerpt = SPListHelper.GetColumnStringValue(_workitem, "LISPPostExcerpt");
                    _workPost.RollupImage = SPListHelper.GetColumnStringValue(_workitem, "PublishingRollupImage");
                    _workPost.PostImage = SPListHelper.GetColumnStringValue(_workitem, "LISPPostImage");
                    DateTime PublishedDate = Convert.ToDateTime(SPListHelper.GetColumnStringValue(_workitem, "Modified"));
                    _workPost.Modified = PublishedDate;
                    _workPost.Url = SPListHelper.GetColumnStringValue(_workitem, "EncodedAbsUrl");
                    _workPost.TimeAgo = SPStringExtensions.TimeAgo(PublishedDate);

                    Posts.Add(_workPost);

                }
                
            }

            return Posts;
        }

        public static string getPostsXml()
        {
            DataSet ds = new DataSet("rows");
            ds.Tables.Add(getPostsDataTable());
            return ds.GetXml();
        }

        public static DataTable getPostsDataTable()
        {

            SPSiteDataQuery q = new SPSiteDataQuery();
            q.Lists = "<Lists ServerTemplate='" + ServerTemplate + "'/>";
            q.Query = "<Where><Eq><FieldRef Name='ContentType' /><Value Type='Text'>" + ContentType + "</Value></Eq></Where><OrderBy><FieldRef Name='Modified' Ascending='FALSE' /></OrderBy>";
            q.Webs = "<Webs Scope='SiteCollection' />";
            q.ViewFields = ViewFields.Title + ViewFields.CType + ViewFields.Url;
            q.RowLimit = 100;

            DataTable t = SPContext.Current.Site.RootWeb.GetSiteData(q);
            t.TableName = "row";

            return t;
        }


        private static int getCommentCount(int PostID)
        {
            int postCount = 0;


            //Get the SP Web
            SPWeb web = SPContext.Current.Site.RootWeb;

            //Get the List Instance
            SPList newslist = web.Lists["Comments"];

            //Get a new SPQuery Instance
            SPQuery workQuery = new SPQuery();
            //Create Expressions for the CAMLEx
            var expressions = new List<Expression<Func<SPListItem, bool>>>();
            expressions.Add(x => ((string)x["LISPCommentPostID"]) == PostID.ToString());
            var caml = Camlex.Query().WhereAny(expressions).ToString();

            workQuery.Query = caml;

            postCount = newslist.GetItems(workQuery).Count;

            return postCount;
        }
    }
}
